import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import 'font-awesome/css/font-awesome.css'

import {postRequest} from "./utils/api";
import {putRequest} from "./utils/api";
import {getRequest} from "./utils/api";
import {deleteRequest} from "./utils/api";
import {initMenu} from "@/utils/menus";
import {downloadRequest} from "@/utils/download";

Vue.config.productionTip = false
Vue.use(ElementUI,{size:'small'});

// 挂载
Vue.prototype.postRequest = postRequest;
Vue.prototype.putRequest = putRequest;
Vue.prototype.getRequest = getRequest;
Vue.prototype.deleteRequest = deleteRequest;
Vue.prototype.downloadRequest=downloadRequest;

/**
 * 全局前置守卫，类似于拦截器
 * to ： 要跳转到那里去
 * from ： 从哪里跳转
 */
router.beforeEach((to, from, next) => {
    // 判断用户是否登录
    if (window.sessionStorage.getItem("tokenStr")) {
        initMenu(router, store);
        // 判断用户信息是否存在,不存在就获取并存入sessionStorage
        if (!window.sessionStorage.getItem('user')){
            return getRequest('/admin/info').then(result=>{
                if (result){
                    // 存入用户信息
                    window.sessionStorage.setItem('user',JSON.stringify(result));
                    next();
                }
            })
        }
        next();
    } else {
        // 未登录时：判断 to.path 是否是登录页面
        if (to.path === '/') {
            next();
        } else {
            // 未登录，重定向跳转登录页面
            next('/?redirect=' + to.path);
        }
    }
})

new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app')
